package pers.cz.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import pers.cz.chat.constants.JefClolorEnum;
import pers.cz.chat.utils.LogUtils;
import pers.cz.netty.filter.IFilter;
import pers.cz.netty.handle.ServerMessageHandler;
import pers.cz.netty.protocal.Message;

import java.util.Arrays;

/**
 * @program: Jef-Chat
 * @description: 消息处理器
 * @author: Cheng Zhi
 * @create: 2024-12-15 20:02
 **/
@ChannelHandler.Sharable
public class MessageForwardHandle extends ServerMessageHandler {

    private IFilter<Message, Channel> iFilter;

    public void setFilter(IFilter<Message, Channel> filter) {
        this.iFilter = filter;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {

        LogUtils.print(JefClolorEnum.WHITE,"收到消息：{}", message.getContent());

        if (iFilter != null && iFilter.doFilter(message, channelHandlerContext.channel())) {
            channelHandlerContext.fireChannelRead(message);
            return;
        }
        // 转发消息给指定客户端
        String targetUser = message.getAttachment("target");

        // 判断targetUser是普通用户还是群组
        if (targetUser.startsWith("group-")) {
            // 如果是群组广播给每个人
            String[] group = GroupManager.getGroup(targetUser);
            if (group != null && group.length > 0) {
                message.addAttachment("source", "群聊" + targetUser + "中" + message.getAttachment("source"));
                Arrays.stream(group).filter(user -> !user.equals(message.getAttachment("username"))).forEach(user -> {send(channelHandlerContext, message, user);});
                return;
            }
        }

        send(channelHandlerContext, message, targetUser);
    }

    private void send(ChannelHandlerContext channelHandlerContext, Message message, String targetUser) {
        Channel userChannel = UserManager.getUserChannel(targetUser);

        if (userChannel == null || !userChannel.isActive()) {
            LogUtils.print(JefClolorEnum.YELLOW,"对方不活跃！");
            message.setContent("对方不在线！");
            message.addAttachment("source", "server");
            channelHandlerContext.writeAndFlush(message);
            return;
        }

        ChannelFuture f = userChannel.writeAndFlush(message);
        f.addListener((ChannelFuture future) -> {
            if (!future.isSuccess()) {
                Throwable cause = future.cause();
                if (cause != null) {
                    LogUtils.print(JefClolorEnum.YELLOW, "发送失败，原因: {}", cause.getMessage());
                } else {
                    LogUtils.print(JefClolorEnum.YELLOW, "发送失败，但没有获取到具体原因。");
                }
            } else {
                LogUtils.print(JefClolorEnum.GREEN, "消息发送成功。");
            }
        });

        channelHandlerContext.fireChannelRead(message);
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        // 断开下线
        UserManager.markOffline(ctx.channel());
        super.channelInactive(ctx);
    }
}
